
#include <QDebug>
#include <Core/QWavFile.hpp>

using namespace AudioCore;


QWavFile::QWavFile(QString path, QObject *parent /*=0*/):QIODevice(parent), mWavFile(path, parent),isOpen(false)
{
    if(!isOpen)
    {
        isOpen=open();
    }
}

QWavFile::~QWavFile()
{

}



qint64 QWavFile::readData(char *data, qint64 len)
{
    return mWavFile.read( data, len);
}

qint64 QWavFile::writeData(const char *data, qint64 len)
{
    Q_UNUSED(data);
    Q_UNUSED(len);
    return 0;
}

qint64 QWavFile::bytesAvailable() const
{
    qDebug() << "Get byte Availible";
    qDebug() << (int)(mWavFile.bytesAvailable());
    return mWavFile.bytesAvailable();
}

bool QWavFile::open(QIODevice::OpenMode mode)
{
    return QIODevice::open(mode);
}

QAudioFormat QWavFile::getAudioFormat()
{
    qDebug() << "Return audio Format";
    qDebug() << mAudioFormat.codec();
    qDebug() << mAudioFormat.channelCount();
    qDebug() << mAudioFormat.sampleRate();
    return mAudioFormat;
}

bool QWavFile::isReady()
{
    return true;
}

QString QWavFile::getState()
{
    return "OK";
}

bool QWavFile::readWaveHeader()
{
    WavHeader header;
    bool result = false;

    Q_ASSERT( sizeof(header) == wav_header_length );

    int len = static_cast<int> ( mWavFile.read( (char *) &header, wav_header_length) );
    if( len == -1 )
    {
        qDebug() << "File read error";
        qDebug() << mWavFile.errorString();
    }
    else
    {
        Q_ASSERT( len == wav_header_length );

        qDebug() << "Header was read succesfully";
        qDebug() << "***************************";
        qDebug() << "Chanels: " << header.NumChannells;
        qDebug() << "Depth: " << header.BitPerSample << " bit";
        qDebug() << "Sample Rate: " << header.SampleRate << " Hz";
        qDebug() << sizeof(header);
        qDebug() << "Possition"  << mWavFile.pos();

        // Set audio format
        mAudioFormat.setChannelCount( header.NumChannells );
        mAudioFormat.setSampleRate( header.SampleRate );
        mAudioFormat.setSampleSize( header.BitPerSample );
        mAudioFormat.setCodec("audio/pcm");
        mAudioFormat.setByteOrder(QAudioFormat::LittleEndian);
        mAudioFormat.setSampleType( QAudioFormat::SignedInt );

        result = true;
    }

    return result;
}

bool QWavFile::open()
{

    bool result=false;

    if( mWavFile.open(QFile::ReadOnly) )
    {
        result = readWaveHeader();
    }

    return result;

}




